//
//  FoodViewController.m
//  B
//
//  Created by lanou on 16/5/10.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "FoodViewController.h"
#import "FoodSearchTableViewController.h"
#import "UIView+QHExtension.h"
#import "FoodTableViewCell.h"
#import "FoodCollectionViewCell.h"
#import "MoreTableViewCell.h"

static NSString *CellIdentifier = @"Cell";

@interface FoodViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) NSArray *listArrs;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@end

@implementation FoodViewController

- (NSMutableArray *)sectionCountArrs
{
    if (!_sectionCountArrs) {
        _sectionCountArrs = [NSMutableArray array];
    }
    return _sectionCountArrs;
}

- (NSArray *)listArrs
{
    if (!_listArrs) {
        _listArrs = [NSArray array];
    }
    return _listArrs;
}
- (void)viewWillAppear:(BOOL)animated {
    self.sectionCountArrs = [[[NSUserDefaults standardUserDefaults] objectForKey:@"23333"] mutableCopy];
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    self.nameTF = [[UITextField alloc] initWithFrame:view.frame];
    _nameTF.borderStyle = UITextBorderStyleRoundedRect;
    _nameTF.placeholder = @"请输入食物名称";
    [view addSubview:_nameTF];
    self.navigationItem.titleView = view;
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(search)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self subviews];
}


- (void)subviews
{
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.itemSize = CGSizeMake(self.view.frame.size.width / 2, 40);
    _layout.minimumInteritemSpacing = 0;
    _layout.minimumLineSpacing = 0;
    _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _layout.headerReferenceSize = CGSizeMake(100, 30);
    
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.collectionView];
    [self.collectionView registerNib:[UINib nibWithNibName:@"FoodCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MoreTableViewCell" bundle:nil] forCellReuseIdentifier:@"moreCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"FoodTableViewCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"FoodCollectionViewCell" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self requestData];
    
}

- (void)requestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://food.boohee.com/fb/v1/keywords" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.listArrs = responseObject[@"keywords"];
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)search
{
    if (_nameTF.text.length == 0) {
        [self.view popMessageWithTitle:@"输入不能为空哦,亲" postion:CENTER];
    } else {
        FoodSearchTableViewController *search = [[FoodSearchTableViewController alloc] init];
        search.name = self.nameTF.text;
        if (self.sectionCountArrs.count > 4) {
            [self.sectionCountArrs removeObjectAtIndex:0];
        }
        if (![self.sectionCountArrs containsObject:self.nameTF.text]) {
            [self.sectionCountArrs addObject:self.nameTF.text];
        }
        
        [self.navigationController pushViewController:search animated:NO];
        [self.tableView reloadData];
        [self.collectionView reloadData];
    }
}

#pragma mark - tableView代理
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.sectionCountArrs.count > 0) {
        return @"最近搜过";
    } else {
        return 0;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.sectionCountArrs.count > 0) {
        self.tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, 40 * (self.sectionCountArrs.count + 1) + 50);
        self.collectionView.frame = CGRectMake(0, self.tableView.frame.size.height + 64, self.view.frame.size.width, 300);
        return (self.sectionCountArrs.count + 1);
    } else {
        self.collectionView.frame = CGRectMake(0, 64, self.view.frame.size.width, 300);
        return 0;
    }    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == self.sectionCountArrs.count) {
        MoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"moreCell" forIndexPath:indexPath];
        return cell;
    } else {
        FoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        if (cell == nil)
        {
            cell = [[FoodTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.nameLable.text = self.sectionCountArrs[indexPath.row];
        cell.imageView1.image = [UIImage imageNamed:@"icon_my_appraise_time"];
        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != self.sectionCountArrs.count) {
        FoodSearchTableViewController *search = [[FoodSearchTableViewController alloc] init];
        search.name = self.sectionCountArrs[indexPath.row];
        [self.navigationController pushViewController:search animated:YES];
    }
    if (indexPath.row == self.sectionCountArrs.count) {
        self.sectionCountArrs = nil;
        [self.tableView reloadData];
    }
    
}

#pragma mark - collectionView代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.listArrs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FoodCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.nameLable.text = self.listArrs[indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
  
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor colorWithWhite:0.961 alpha:1.000];
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, headerView.frame.size.height)];
    name.text = @"大家都在搜";
    [headerView addSubview:name];
    return headerView;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FoodSearchTableViewController *search = [[FoodSearchTableViewController alloc] init];
    search.name = self.listArrs[indexPath.row];
    

    if (![self.sectionCountArrs containsObject:search.name]) {
        [self.sectionCountArrs addObject:search.name];
        if (self.sectionCountArrs.count > 4) {
            [self.sectionCountArrs removeObjectAtIndex:0];
        }
    }
    [self.navigationController pushViewController:search animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSUserDefaults standardUserDefaults] setObject:self.sectionCountArrs forKey:@"23333"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
